package com.cloud.basic.Advance.Design.Flyweight_Pattern;

import org.checkerframework.checker.units.qual.C;
import org.springframework.util.ObjectUtils;

import java.util.Hashtable;

/**
 * @program: basic
 * @description: 棋子工厂类(享元工厂)
 * @author: Cloud
 * @create: 2022/2/23 14:40:01
 */
public class ChessmanFactory {

    // 单例模式工厂
    private static ChessmanFactory chessmanFactory = new ChessmanFactory();

    // 缓存存放共享对象
    private final Hashtable<Character,AbstractChessman> cache = new Hashtable<>();

    // 私有化构造方法
    private ChessmanFactory() {
    }

    // 获得单例工厂
    public static ChessmanFactory getInstance() {
        return chessmanFactory;
    }

    /*
     * 功能描述:根据字符获得棋子
     *           B：黑棋 W：白棋）
     * @param c
     * @return com.cloud.basic.Advance.Design.Flyweight_Pattern.AbstractChessman
     * @author cloud
     * @date  2022/2/23 14:45
     */
    public AbstractChessman getChessmanObject(char c) {
        // 从缓存中获得棋子对象实例
        AbstractChessman abstractChessman = this.cache.get(c);

        if (ObjectUtils.isEmpty(abstractChessman)) {
            // 缓存中没有棋子对象实例信息 则创建棋子对象实例 并放入缓存
            switch (c) {
                case 'B':
                    abstractChessman = new BlackChessman();
                    break;
                case 'W':
                    abstractChessman = new WhiteChessman();
                    break;
                default:
                    break;
            }
            // 为防止非法字符的进入 返回null
            if (abstractChessman != null) {
                // 放入缓存
                this.cache.put(c,abstractChessman);
            }
        }
        return abstractChessman;
    }
}
